package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BusinessErrorCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 *
 * @author mingbowang
 * @email wangmignbo@qq.com
 * @date 2021-07-11 10:36 AM
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题: {}，异常类型: {}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();

        Map<String, String> errorMap = new HashMap<>();
        // 1、获取校验的错误结果
        result.getFieldErrors().forEach(x -> {
            // FieldError 获取到错误提示
//            String message = x.getDefaultMessage();
            // 获取错误属性的名字
//            String field = x.getField();
            errorMap.put(x.getDefaultMessage(), x.getField());
        });
        return R.error(BusinessErrorCodeEnum.VALID_EXCEPTION).put("data", errorMap);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.error("异常错误: {}，异常类型: {}", e.getMessage(), e.getClass());
        return R.error(BusinessErrorCodeEnum.UNKNOW_EXCEPTION);
    }

}
